package server

import (
	"context"
	"fmt"
	"github.com/go-kratos/kratos/v2/errors"
	"github.com/go-kratos/kratos/v2/middleware"
	"github.com/go-kratos/kratos/v2/middleware/auth/jwt"
	"github.com/go-kratos/kratos/v2/transport"
	"github.com/go-kratos/kratos/v2/transport/http"
	jwtv4 "github.com/golang-jwt/jwt/v4"
)

func customerJWT() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (interface{}, error) {
			claims, ok := jwt.FromContext(ctx)
			fmt.Println(claims, ok)
			if !ok {
				// 没有获取到 claims
				return nil, errors.Unauthorized("UNAUTHORIZED", "claims not found")
			}
			// 1.2 断言使用
			claimsMap := claims.(jwtv4.MapClaims)
			if _, ex := claimsMap["user_id"]; !ex {
				return nil, errors.Unauthorized("UNAUTHORIZED", "claims not found user_id")
			}
			ctx = context.WithValue(ctx, "user_id", claimsMap["user_id"])

			// todo 后边需要的时候添加 jwt合法验证通过服务端存储

			return handler(ctx, req)
		}
	}
}

// MWCors 跨域资源共享的中间件
func MWCors() middleware.Middleware {
	return func(handler middleware.Handler) middleware.Handler {
		return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
			if tr, ok := transport.FromServerContext(ctx); ok {
				// Do something on entering
				// 在响应中增加特定的头信息
				ht := tr.(http.Transporter)
				ht.ReplyHeader().Set("Access-Control-Allow-Origin", "*")
				ht.ReplyHeader().Set("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,PATCH,DELETE")
				ht.ReplyHeader().Set("Access-Control-Allow-Credentials", "true")
				ht.ReplyHeader().Set("Access-Control-Allow-Headers", "Content-Type,User-Agent,Content-Length,Authorization,Accept,Referer,Host")

				defer func() {
					// Do something on exiting
				}()
			}
			return handler(ctx, req)
		}
	}
}
